<?php
/**
 * 新API工具类
 */
class Api
{
    /**
     * 数据包的签名token
     * 
     * @var string
     */
    private static $signaturePackToken = '5XN%6mMXQ5U$RI^n';

    /**
     * API地址配置
     * 
     * @var unknown
     */
    private static $apiAddrs = array(
        'produce' => array( // 正式环境
            'item' => array(
                'version' => 'v1',
                'addr' => 'http://item.52ywy.com'
            )
        ),
    
        'test' => array( // 测试环境
            'item' => array(
                'version' => 'v1',
                'addr' => 'http://test-newitem.52ywy.com'
            )
        ),
    
        'dev' => array( // 开发环境
            'item' => array(
                'version' => 'v1',
                'addr' => 'http://dev.item.52ywy.com'
            )
        )
    );
    
    /**
     * 调用item模块接口 根据URI
     *
     * @param unknown $class
     * @param unknown $method
     * @param array $data
     */
    public static function callItemApiByUri($uri, $data = array())
    {
        // API 地址
        $apiInfo = self::$apiAddrs[RUN_ENV]['item'];
        $uri = "/{$apiInfo['version']}{$uri}";
        $dataSignature = self::getDataSignature($uri, $data);
        $apiUrl = $apiInfo['addr'] . $uri;
        $header = self::getHeader($dataSignature);
        $result = self::call($apiUrl, $data, $header);
        return $result;
    }

    /**
     * 调用item模块接口
     * 
     * @param unknown $class            
     * @param unknown $method            
     * @param array $data            
     */
    public static function callItemApi($class, $method, $data = array())
    {
        // API 地址
        $apiInfo = self::$apiAddrs[RUN_ENV]['item'];
        $uri = "/{$apiInfo['version']}/{$class}/{$method}";
        $dataSignature = self::getDataSignature($uri, $data);
        $apiUrl = $apiInfo['addr'] . $uri;
        $header = self::getHeader($dataSignature);
        $result = self::call($apiUrl, $data, $header);
        return $result;
    }

    /**
     * 获取数据包签名串
     * 
     * @param string $uri            
     * @param array $data            
     * @return string
     */
    protected static function getDataSignature($uri, $data = array())
    {
        $gather = '';
        if (! empty($data) && is_array($data)) {
            foreach ($data as $k => $v) {
                if ($gather != "") {
                    $gather .= '&';
                }
                $gather .= "{$k}={$v}";
            }
        }
        $signature = md5(self::$signaturePackToken . $uri . $gather);
        return $signature;
    }

    /**
     * 获取请求API头
     * 
     * @param string $dataSignature            
     */
    protected static function getHeader($dataSignature)
    {
        $header = array();
        $header['X-Real-Ip'] = $_SERVER['REMOTE_ADDR']; // 真实IP地址
//         $header['Connection'] = 'keep-alive'; // 保持长连接,TODO,没有复用链接，等待解决？
        $header['Data-Signature'] = $dataSignature;
        $header['Client-Platform'] = 3;
//         $header['Member-Id'] = MEMBER_ID;
//         $header['Member-Signature'] = MEMBER_SIGNATURE;
//         $header['Micro-Shop-Id'] = 0;
        $headerStrArr = array();
        foreach ($header as $k => $v) {
            $headerStrArr[] = "{$k}:{$v}";
        }
        return $headerStrArr;
    }

    /**
     * 调用API
     * 
     * @param string $addr            
     * @param array $data            
     * @param array $header            
     */
    protected static function call($addr, $data, $header)
    {
        global $config;
        include_once($config["webroot"]."/lib/Helper.php");
        $res = Helper::curl_file_get_contents($addr, $data, $header);
        if (empty($res)) {
            return ["code"=>"1111","msg"=>"the api {$addr} response data is empty"];
        }
        $data = json_decode($res, true);
        if (!is_array($data) || count($data)<=0) {
            return ["code"=>"1212","msg"=>"the api server response data type is\'nt JSON"];
        }
        return $data;
    }
}